<!doctype html>
<html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false"%>
<head>
    <title>宏电视频监控</title>
    <%@ include file="videoHead.jsp"%>
</head>
<body onUnload="stopRealPlay()" >
<div class="row-fluid" style="height:100%;">
	<div class="span7" style="height:100%;float: left;">
		<object id="IScanClientOCXCtrl" style="z-index:-100; width:100%; height:100% ; float:right; "  codebase="download/IScanClientOCX.exe" classid="clsid:455FA7A9-756E-4767-8A0A-40DDECD23659">
		</object>
	</div>
	<div class="span5" style="height:100%;float: left;margin-left:0px;">
		<div id="gdMap"  style="height:60%;width:100%"></div>
		<div id="speedDiv" style="height:40%;width:100%" >
			<div id="speedCharts" style="width:100%;height: 100%;"></div>
		</div>
		<div id="tooldiv" style="position: absolute;z-index: 99;right: 20px;top:10px;background-color: white;">
		<button onclick="downloadVideoControl()">下载视频控件</button>
		<select style="width:130px;margin: 0px;" id="timeOutSel">
		<option value ="300" selected="selected">5分钟后关闭</option>
  		<option value ="600">10分钟后关闭</option>
  		<option value="1200">20分钟后关闭</option>
  		<option value="1800">30分钟后关闭</option>
  		</select>
  		<div class="timeEnd">
  			<span id="t_m">00分</span> 
			<span id="t_s">00秒</span>
  		</div>
		<button id="closeVideoDiv" >关闭视频</button>
		<select id="selectVehicleSel" onchange="changeVechile()"  style="width:100px;margin: 0px;">
		</select>
	</div>
	</div>
	
</div>
<!-- 用于控制弹出窗口- -->
<a id="txtOpenWindow" target="_self" style="display: none"></a>

<script>


	
	

var oneDay = 10 * 1000;
var date = [];

var data = [];
var now = new Date();
var nowstr="";
var vehicleID ="${vehicleID}";
var commno ="${commno}";
var regNO ="${registrationNO}";
var internal_number ="${internal_number}";

var vehicleNO ="${vehicleNO}";
var videoOverTime = ${ownerSetting.videoOverTime!=null?ownerSetting.videoOverTime:60}; 
var fileVersion = "1.0.1.0";//当前版本号

var RegistrationNO ='${RegistrationNO}';
var user='${user}';
var password='${password}';
var ip='${ip}';   
var port='${port}';
var deviceId='${deviceId}';

var intsetInterval=0;
var isinitselect = true;
var  appCtx="${appCtx}";
var defaultTime =60;
var trackArray=new Array(); 

var intsetIntervalSub=0;
var curgpstime="";
var curaddress="";

var infoWindow;
var marker,map = new AMap.Map('gdMap', {
    resizeEnable: true,
    zoom:11,
    center: [116.397428, 39.90923]
});

$(function(){ 
	try{
		initVehicleList();
		 defaultTime =$("#timeOutSel").val();
		 setTimeout("afterrender()", 3000 ); 
		 intsetInterval=window.setInterval("timeOut();", 1000);
		 intsetIntervalSub=window.setInterval("subScribeVehicle();", 1000);
		 $("#closeVideoDiv").unbind("click");
		 $("#closeVideoDiv").bind("click",buttonCloseVideo);
		 $("#closeVideoDiv").html("关闭视频")
	}catch(e){
		  
	}
});    

var n=1;
var m=1;
function subScribeVehicle(){
	
	 $.ajax({
         url : appCtx+'gis/monitor/subScribe.html?commnos='+commno,
         method : 'GET',
         dataType :'json',
         success : function(datar){
        	 datar=[{"carStatus":3,"flag":0,"gpsMileage":0,"gpsSpeed":0,"gpsTime":0,"gpsTimeStr":"2017-06-12 13:54:05","latitude":23.174663,"longitude":113.40649,"terminalId":10,"terminalType":0,"vehicleId":10}];
             datar[0].gpsTimeStr=datar[0].gpsTimeStr.substring(0,18)+m;
        	 if(datar&&datar.length>0){
            	 n++;
            	 m++;
            	 if(n>59){
            		 n=0;
            	 }
            	 if(m>9){
            		 m=0
            	 }
            	 
            	 //[{"carStatus":3,"flag":0,"gpsMileage":0,"gpsSpeed":0,"gpsTime":0,"gpsTimeStr":"2017-06-12 13:54:05","latitude":23.174663,"longitude":113.40649,"terminalId":10,"terminalType":0,"vehicleId":10}]
            	 if(curgpstime!=datar[0].gpsTimeStr){
            		 var arrgps=[];
            		 arrgps.push(datar[0].longitude+n*0.001);
            		 arrgps.push(datar[0].latitude+n*0.001);
            		 initInfo(datar[0]);
            		 if(trackArray.length==0){
            			 	marker = new AMap.Marker({
            		            icon: "http://webapi.amap.com/theme/v1.3/markers/n/mark_b.png",
            		            position: [datar[0].longitude+n*0.001, datar[0].latitude+n*0.001]
            		        });
            		        marker.setMap(map);
            		        AMap.event.addListener(marker,'click',openInfo);
            		 }else{
            			  marker.setPosition([datar[0].longitude+n*0.001, datar[0].latitude+n*0.001]); //更新点标记位置
            		 }
            		 trackArray.push(arrgps);
            		 
            		 if(trackArray.length>2){
            			 trackArray.shift();
            		 }
            		 
            		 if(trackArray.length==2){
            			 	var polyline = new AMap.Polyline({
            			        path: trackArray,          //设置线覆盖物路径
            			        strokeColor: "#3366FF", //线颜色
            			        strokeOpacity: 1,       //线透明度
            			        strokeWeight: 5,        //线宽
            			        strokeStyle: "solid",   //线样式
            			        strokeDasharray: [10, 5] //补充线样式
            			    });
            			    polyline.setMap(map);
            		 }
            		 map.setCenter(new AMap.LngLat(datar[0].longitude+n*0.001, datar[0].latitude+n*0.001))
            		 
            		 curgpstime=datar[0].gpsTimeStr;
            		 date.push(datar[0].gpsTimeStr);
                	 data.push(/* datar[0].gpsSpeed */60);
                	 updatemyChart();
            	 }
             }
         }
     });
}


function initInfo(data){
	var lnglatXY = [data.longitude+n*0.001,data.latitude+n*0.001]; //已知点坐标
    var geocoder = new AMap.Geocoder({
         radius: 1000,
         extensions: "all"
     });        
     geocoder.getAddress(lnglatXY, function(status, result) {
         if (status === 'complete' && result.info === 'OK') {
             curaddress=result.regeocode.formattedAddress;  
         }
     });  
       
   //构建信息窗体中显示的内容
   var info = [];
   info.push("<div><div><img style=\"float:left;\" /></div> ");
   info.push("<div style=\"padding:0px 0px 0px 4px;\"><b>车牌号："+regNO+"     自编号："+internal_number+"</b>");
   info.push("定位时间 ："+data.gpsTimeStr+"   里程："+data.gpsMileage+"          速度："+data.gpsSpeed);
   info.push("当前位置 ："+curaddress+"</div></div>");
   infoWindow = new AMap.InfoWindow({
       content: info.join("<br/>")  //使用默认信息窗体框样式，显示信息内容
   });
}
//在指定位置打开信息窗体
function openInfo() {
    infoWindow.open(map, map.getCenter());
}


function initVehicleList(){
	$.ajax({
		type : 'post',
		async : false,
		url : appCtx + "/video/queryVideoVehicleList.html",
		cache : false,
		dataType : "JSON",
		success : function(data) {
			if(data){

				$('#selectVehicleSel').select2({
				  data: data
				})
				
				$('#selectVehicleSel').val(vehicleID).trigger("change");
			}
		}
	});

}

function timeOut(){
	if(defaultTime>0){
		defaultTime--;
		var m=Math.floor(defaultTime/60%60); 
		var s=Math.floor(defaultTime%60);
		if(m<10){
			document.getElementById("t_m").innerHTML = "0"+m + "分"; 
		}else{
			document.getElementById("t_m").innerHTML = m + "分"; 
		}
		if(s<10){
			document.getElementById("t_s").innerHTML = "0"+s + "秒";
		}else{
			document.getElementById("t_s").innerHTML = s + "秒";
		}
	}else{
		document.getElementById("t_m").innerHTML = "00" + "分";
		document.getElementById("t_s").innerHTML = "00" + "秒";
		window.clearInterval(intsetInterval);
		stopRealPlay();  
		$("#closeVideoDiv").unbind("click");
		$("#closeVideoDiv").bind("click",buttonOpenVideo);
		$("#closeVideoDiv").html("打开视频")
	}
}

function buttonOpenVideo(){
	 defaultTime =$("#timeOutSel").val();
	 realPlay();
	 intsetInterval=window.setInterval("timeOut();", 1000);
	 $("#closeVideoDiv").unbind("click");
	 $("#closeVideoDiv").bind("click",buttonCloseVideo);
	 $("#closeVideoDiv").html("关闭视频")
}
function buttonCloseVideo(){
	defaultTime=0;
	document.getElementById("t_m").innerHTML = "00" + "分";
	document.getElementById("t_s").innerHTML = "00" + "秒";
	window.clearInterval(intsetInterval);
	stopRealPlay();
	$("#closeVideoDiv").unbind("click");
	$("#closeVideoDiv").bind("click",buttonOpenVideo);
	$("#closeVideoDiv").html("打开视频")
}/* 
function setTimeOut(){
	realPlay();
	 $("#resetTimeout").hide();
	 $("#time_label").show();
	defaultTime = videoOverTime;
} */
IScanClientOCXCtrlParam = function(){ 
    return {
        resultInitial:null,
        resultLogin:null,
        videoCtrl : new Array(17),//针对通道，包括通道信息(data:object)、是否打开声音(sound:bool)，从1开始
        curPresetControl : -1, //39表示调用，8表示设置，9表示删除
        talkCtrl : null,//已打开对讲的设备信息,
		talkDevAddr: null, // 已打开对讲设备地址
		talkDevName: null, // 已打开对讲设备名
        deviceAddress:null,//设备地址
        devName:null,
        state:null,//判断是否已经登录
        picturePath : 'D:\\iscanPicture\\',
        vedioPath : 'D:\\iscanVedio\\',
        groupsCtrl: new Array(64),
        sound_first:0,//获取窗口消息，实时存取窗口号
        sound_third:0,//打开声音后的窗口号
        sound_fouth:0,//打开第二个窗口后，存放第一个窗口号
        errorInfo :['没有对讲权限','登录dns服务器失败','连接流媒体服务器失败','网络响应超时','网络错误','由于网络原因或DVR忙，注册失败（连接服务器失败）',
            '超过了用户所在机构下的最大输出流','超过了流媒体的最大输出数限制','超过了服务器最大的输出流','没有视频监控权限','未知错误',
            '连续登录失败次数超过限定，用户将被锁定一段时间','多次登录失败，需退出程序','用户密钥错误','用户已过期','版本不匹配',
            '用户被禁用','用户已经登录','服务器地址无效','用户没有权限','用户名或密码错误','连接服务器失败','无效参数','内存错误',
            '没有登录','参数没有初始化','登录失败','登录成功'],
        destroy : function(){
            this.videoCtrl = new Array(17);
            this.talkCtrl = null;
            this.deviceAddress = null;
            this.state = null;
            this.picturePath = 'D:\\iscanPicture\\';
            this.vedioPath = 'D:\\iscanVedio\\';
			this.talkDevAddr = null;
			this.talkDevName = null;
        }
    }
}();

function afterrender(){
   
	login();
	
	setTimeout(function(){
		realPlay();
	},5000)
    
}
//键盘控制回车登录事件；
document.onkeydown = function(e){
    e = window.event || e;
    var ke = e.keyCode || e.which;
    if(13 == ke){
        login();
    }
}  
//登录
function login(){ 
    if(IScanClientOCXCtrlParam.state){
        alert("请退出系统再重新登录");
        return;
    }
     //user = "yccs";
     //password = "123456";
     //ip = "211.162.75.141";
     //port = "52460";
   
    if(!user||!password||!ip||!port){
        alert('用户名、密码、ip或端口号为空');
        return;
    }
    var resultInitial = IScanClientOCXCtrl.CX_Initial(ip, port, '0', '3');
    if(0 != resultInitial){
        alert('插件初始化失败,请检查是否安装!')
        return;
    }
    var resultLogin = IScanClientOCXCtrl.CX_Login(user, password);
    for(var i = 0;i < IScanClientOCXCtrlParam.errorInfo.length;i++){
        if((resultLogin + 27) == 27){ 
           
            IScanClientOCXCtrlParam.state = true;
          
            break;
        }else if(i == (resultLogin + 27)){
            var errorInfo = IScanClientOCXCtrlParam.errorInfo[i]
            alert(errorInfo);//输出错误信息
            return;
        }
    }
    IScanClientOCXCtrlParam.resultInitial = resultInitial;
    IScanClientOCXCtrlParam.resultLogin = resultLogin;
    var deviceList = IScanClientOCXCtrl.CX_GetDeviceList();
   
}


//实时预览
function realPlay(){ 
    if(0 == IScanClientOCXCtrlParam.resultInitial && 0== IScanClientOCXCtrlParam.resultLogin){
 
        var result = IScanClientOCXCtrl.CX_RealPlay(0, deviceId, 1, 0);
        if(0 == result){
            IScanClientOCXCtrlParam.videoCtrl[0] = new Object();
            IScanClientOCXCtrlParam.videoCtrl[0].devAddress = deviceId;
            IScanClientOCXCtrlParam.videoCtrl[0].channelNum = 1;
            IScanClientOCXCtrlParam.videoCtrl[0].devName = RegistrationNO;
            IScanClientOCXCtrlParam.videoCtrl[0].sound = false;
            IScanClientOCXCtrl.CX_PTZControl(0,8,63,0);
        }
		var result2 = IScanClientOCXCtrl.CX_RealPlay(1, deviceId, 2, 1);
        if(0 == result2){
            IScanClientOCXCtrlParam.videoCtrl[1] = new Object();
            IScanClientOCXCtrlParam.videoCtrl[1].devAddress = deviceId;
            IScanClientOCXCtrlParam.videoCtrl[1].channelNum = 2;
            IScanClientOCXCtrlParam.videoCtrl[1].devName = RegistrationNO;
            IScanClientOCXCtrlParam.videoCtrl[1].sound = false;
            IScanClientOCXCtrl.CX_PTZControl(1,8,63,0);
        }
		var result3 = IScanClientOCXCtrl.CX_RealPlay(2, deviceId, 3, 2);
        if(0 == result3){
            IScanClientOCXCtrlParam.videoCtrl[2] = new Object();
            IScanClientOCXCtrlParam.videoCtrl[2].devAddress = deviceId;
            IScanClientOCXCtrlParam.videoCtrl[2].channelNum = 3;
            IScanClientOCXCtrlParam.videoCtrl[2].devName = RegistrationNO;
            IScanClientOCXCtrlParam.videoCtrl[2].sound = false;
            IScanClientOCXCtrl.CX_PTZControl(2,8,63,0);
        }
		var result4 = IScanClientOCXCtrl.CX_RealPlay(3, deviceId, 4, 3);
        if(0 == result4){
            IScanClientOCXCtrlParam.videoCtrl[3] = new Object();
            IScanClientOCXCtrlParam.videoCtrl[3].devAddress = deviceId;
            IScanClientOCXCtrlParam.videoCtrl[3].channelNum = 4
            IScanClientOCXCtrlParam.videoCtrl[3].devName = RegistrationNO;
            IScanClientOCXCtrlParam.videoCtrl[3].sound = false;
            IScanClientOCXCtrl.CX_PTZControl(3,8,63,0);
        }
        soundOpen();
    }
}
//
function  stopRealPlay(){
    if(0 == IScanClientOCXCtrlParam.resultInitial && 0== IScanClientOCXCtrlParam.resultLogin){
    	var port0 = IScanClientOCXCtrl.CX_GetPlayPortByWndNum(0);
        var result0 = IScanClientOCXCtrl.CX_StopRealPlay(0);
        var port1 = IScanClientOCXCtrl.CX_GetPlayPortByWndNum(1);
        var result1 = IScanClientOCXCtrl.CX_StopRealPlay(1);
        var port2 = IScanClientOCXCtrl.CX_GetPlayPortByWndNum(2);
        var result2 = IScanClientOCXCtrl.CX_StopRealPlay(2);
    	var port3 = IScanClientOCXCtrl.CX_GetPlayPortByWndNum(3);
        var result3 = IScanClientOCXCtrl.CX_StopRealPlay(3);
        if(0 == result1){
        	IScanClientOCXCtrlParam.videoCtrl[0] = null;
        	IScanClientOCXCtrlParam.videoCtrl[1] = null;
        	IScanClientOCXCtrlParam.videoCtrl[2] = null;
        	IScanClientOCXCtrlParam.videoCtrl[3] = null;
        }else{
            alert('停止预览失败，请确认该窗口视频是否打开！')
        }
        //soundClose();
        
    }
}

//打开声音
function soundOpen(){
    if(0 == IScanClientOCXCtrlParam.resultInitial && 0== IScanClientOCXCtrlParam.resultLogin){    
        var port1 = IScanClientOCXCtrl.CX_GetPlayPortByWndNum(1);   
        if(IScanClientOCXCtrlParam.videoCtrl[1].sound){
            //                        var res = IScanClientOCXCtrl.CX_StopSound(curSelWinNum);
            //                        IScanClientOCXCtrlParam.videoCtrl[curSelWinNum].sound = false;
            return;
        }else{
            var result1 = IScanClientOCXCtrl.CX_PlaySound(port1);
            if(0 == result1){
                IScanClientOCXCtrlParam.videoCtrl[1].sound = true
            }      
        }
        
        var port2 = IScanClientOCXCtrl.CX_GetPlayPortByWndNum(2);   
        if(IScanClientOCXCtrlParam.videoCtrl[1].sound){
            //                        var res = IScanClientOCXCtrl.CX_StopSound(curSelWinNum);
            //                        IScanClientOCXCtrlParam.videoCtrl[curSelWinNum].sound = false;
            return;
        }else{
            var result2 = IScanClientOCXCtrl.CX_PlaySound(port2);
            if(0 == result2){
                IScanClientOCXCtrlParam.videoCtrl[1].sound = true
            }      
        }
        
        var port3 = IScanClientOCXCtrl.CX_GetPlayPortByWndNum(3);   
        if(IScanClientOCXCtrlParam.videoCtrl[1].sound){
            //                        var res = IScanClientOCXCtrl.CX_StopSound(curSelWinNum);
            //                        IScanClientOCXCtrlParam.videoCtrl[curSelWinNum].sound = false;
            return;
        }else{
            var result3 = IScanClientOCXCtrl.CX_PlaySound(port3);
            if(0 == result3){
                IScanClientOCXCtrlParam.videoCtrl[1].sound = true
            }      
        }


    }
}
//关闭声音
function soundClose(){
    if(0 == IScanClientOCXCtrlParam.resultInitial && 0== IScanClientOCXCtrlParam.resultLogin){
       
        var port1 = IScanClientOCXCtrl.CX_GetPlayPortByWndNum(1);
        if(IScanClientOCXCtrlParam.videoCtrl[1].sound){
            var res1 = IScanClientOCXCtrl.CX_StopSound(port1);
            if(0 == res1){
                IScanClientOCXCtrlParam.sound_first = 0;
                IScanClientOCXCtrlParam.sound_third = 0;
                IScanClientOCXCtrlParam.sound_fouth = 0;
                IScanClientOCXCtrlParam.videoCtrl[1].sound = false;
            }

        }
        var port2 = IScanClientOCXCtrl.CX_GetPlayPortByWndNum(2);
        if(IScanClientOCXCtrlParam.videoCtrl[1].sound){
            var res2 = IScanClientOCXCtrl.CX_StopSound(port2);
            if(0 == res2){
                IScanClientOCXCtrlParam.sound_first = 0;
                IScanClientOCXCtrlParam.sound_third = 0;
                IScanClientOCXCtrlParam.sound_fouth = 0;
                IScanClientOCXCtrlParam.videoCtrl[1].sound = false;
            }

        }
        var port3 = IScanClientOCXCtrl.CX_GetPlayPortByWndNum(3);
        if(IScanClientOCXCtrlParam.videoCtrl[1].sound){
            var res3 = IScanClientOCXCtrl.CX_StopSound(port3);
            if(0 == res3){
                IScanClientOCXCtrlParam.sound_first = 0;
                IScanClientOCXCtrlParam.sound_third = 0;
                IScanClientOCXCtrlParam.sound_fouth = 0;
                IScanClientOCXCtrlParam.videoCtrl[1].sound = false;
            }

        }
    }
}

function addData(shift) {
    var hourstr=now.getHours() < 10 ? "0" + now.getHours() : now.getHours();
    var minutestr=now.getMinutes() < 10 ? "0" + now.getMinutes() : now.getMinutes();
    var secondstr=now.getSeconds() < 10 ? "0" + now.getSeconds() : now.getSeconds();
    nowstr = [hourstr, minutestr, secondstr].join(':');
    date.push(nowstr);
    data.push(parseFloat(Math.random() * 30+50).toFixed(1));

    if (shift) {
        date.shift();
        data.shift();
    }

    now = new Date(+new Date(now) + oneDay);
}



option = {
    xAxis: {
        type: 'category',
        boundaryGap: false,
        data: date
    },
    tooltip: {
        trigger: 'axis',
        formatter: function (params) {
            params = params[0];
            return "时间:"+params.name+"<br/>"+"速度"+params.value;
        },
        axisPointer: {
            animation: false
        }
    },
    yAxis: {
        boundaryGap: [0, '50%'],
        name : '速度(km/h)',
	    type : 'value',
	    max : 150,
    },
    series: [
        {
            name:'速度',
            type:'line',
            smooth:true,
            symbol: 'none',
            stack: 'a',
            areaStyle: {
                normal: {}
            },
            data: data
        }
    ]
};
var myChart = echarts.init(document.getElementById('speedCharts'));
	myChart.setOption(option);
	
function updatemyChart() {
    myChart.setOption({
        xAxis: {
            data: date
        },
        series: [{
            name:'速度',
            data: data
        }]
    });
}

	
//打开新窗体
function openWindow(url){
	var openLink = $("#txtOpenWindow");
	openLink.attr('href', url);
	openLink[0].click();
}

function changeVechile(){
	if(isinitselect){
		isinitselect=false;
	}else{
		if($("#closeVideoDiv").html()=="关闭视频"){
			alert("需要关闭当前正在播放的视频才能进行切换！");
			isinitselect=true;
			$('#selectVehicleSel').val(vehicleID).trigger("change");
		}else{
			try{
				exitstopplay();
			}catch(e){
				
			}
			
			var vid=$("#selectVehicleSel").val();
			openWindow(appCtx + "/video/videoMonitor.html?vehicleID="+vid);
		}
		
	}
}


</script>
</body>
</html>
